package com.zigong.app.ui.activities;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Pair;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.google.gson.Gson;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.dialog.ShareFragment;
import com.zigong.app.R;
import com.zigong.app.base.BaseActivity;
import com.zigong.app.base.BaseDetailActivity;
import com.zigong.app.beans.FNews;
import com.zigong.app.beans.JSBeans;
import com.zigong.app.ui.widget.MyWebChromeClient;
import com.zigong.app.utils.UserManager;
import com.tencent.smtt.export.external.interfaces.IX5WebChromeClient;

import org.json.JSONObject;

import java.io.File;
import java.util.Arrays;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * H5网页显示（当前使用）
 */
public class H5NormalActivity extends BaseDetailActivity {
    @BindView(R.id.webView_h5)
    protected WebView webView;
    @BindView(R.id.webView_video_full_contain)
    protected ViewGroup videoFullContainer;
    private String url;
    private String title;
    private String token;
    private ValueCallback<Uri> uploadFile;
    private ValueCallback<Uri[]> uploadFiles;

    private String mCameraFilePath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        new TitleUtils(this);
        title = getIntent().getStringExtra(EX_TITLE);
        initView();
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_h5_normal);

        ButterKnife.bind(this);
    }

    private void initView() {
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);
        }
//        WebSettings settings = webView.getSettings();
//        // 使用缓存
//        settings.setCacheMode(WebSettings.LOAD_DEFAULT);
//        String ua = settings.getUserAgentString();
//        settings.setUserAgentString(ua + " SCGC_UA");
////        settings.getUserAgentString()
//        //使h5页面适应手机屏幕
//        settings.setUseWideViewPort(true);
//        settings.setLoadWithOverviewMode(true);
//        //设置可以支持缩放
//        settings.setSupportZoom(true);
//        //设置出现缩放工具
//        settings.setBuiltInZoomControls(true);
//        //隐藏缩放工具
//        settings.setDisplayZoomControls(false);
//        //扩大比例的缩放
//        settings.setUseWideViewPort(true);
//        // 支持JavaScript
//        settings.setJavaScriptEnabled(true);
//        settings.setMediaPlaybackRequiresUserGesture(false);

        webView.setWebChromeClient(new MyWebChromeClient() {
            @Override
            public boolean onJsConfirm(WebView arg0, String arg1, String arg2,
                                       JsResult arg3) {
                return super.onJsConfirm(arg0, arg1, arg2, arg3);
            }

            IX5WebChromeClient.CustomViewCallback callback;

            @Override
            public void onHideCustomView() {
                if (callback != null) {
                    callback.onCustomViewHidden();
                }
                if (videoFullContainer == null) {
                    super.onHideCustomView();
                } else {
                    videoFullContainer.removeAllViews();
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//强制竖屏
                    getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                    videoFullContainer.setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void onShowCustomView(View view, CustomViewCallback customViewCallback) {
//                JLog.e("rrrt  view=" + view + "\n  container=" + videoFullContainer);
                if (videoFullContainer == null) {
                    super.onShowCustomView(view, customViewCallback);
                } else {
                    videoFullContainer.addView(view);
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//强制横屏
                    hideStatusBar();
                    videoFullContainer.setVisibility(View.VISIBLE);
                }
            }

//            @Override
//            public void onShowCustomView(View view, int i, CustomViewCallback customViewCallback) {
//                JLog.e("rrrt  view=" + view + "    i=" + i + "\n  container=" + videoFullContainer);
//                super.onShowCustomView(view, i, customViewCallback);
//            }

            @Override
            public boolean onJsAlert(WebView webView, String s, String s1, JsResult jsResult) {
//                JLog.e("rrrt  s=" + s + "\n   s1=" + s1 + "\n result =" + jsResult);
                return super.onJsAlert(webView, s, s1, jsResult);
            }

            // For Android  > 4.1.1
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
//                Log.i("test", "openFileChooser 3");
                H5NormalActivity.this.uploadFile = uploadFile;
                openFileChooseProcess(null);
            }

            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                H5NormalActivity.this.uploadFiles = filePathCallback;
                Intent intent = null;
                if (fileChooserParams != null) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        intent = fileChooserParams.createIntent();
//                        JLog.e("wwww  fp=" + fileChooserParams.getMode() + "   title=" + fileChooserParams.getTitle()
//                                + "\n" + Arrays.toString(fileChooserParams.getAcceptTypes()) + "  " + intent
//                                + "\n" + fileChooserParams.isCaptureEnabled());
//                        if (intent != null) {
//                            toast("use it\'s intent");
//                            startActivityForResult(Intent.createChooser(intent,"chooose"), 0);
//                            return true;
//                        }
                    }
                }

                openFileChooseProcess(intent);
                return true;
            }
        });
        webView.setWebViewClient(new WebViewClient() {
            /**
             * 防止加载网页时调起系统浏览器
             */
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (!url.startsWith("http://") && !url.startsWith("https://")) {
                    return true;
                }
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                String titleStr = view.getTitle();
                if (!TextUtils.isEmpty(titleStr)) {
//                    if (TextUtils.isEmpty(title)){
                    title = titleStr;
//                    }
                }
            }
        });
        webView.addJavascriptInterface(new Object() {
            @JavascriptInterface
            public void callRouter(String s1, String s2) {
                //H5页面调用Android原生代码
                if (!TextUtils.isEmpty(s1)) {
                    try {
                        JLog.e("htmlLogin", "-----------------------s1-" + s1 + "----s2" + s2);
                        JSONObject jso = new JSONObject(s1);
                        JSBeans jsonBean = new Gson().fromJson(s1, JSBeans.class);
                        parseJSMethod(jsonBean.getMethod(), jsonBean.getActId());
//                        String actId =
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

        }, "bridge");
        initX5Setting();
        Intent intent = getIntent();
        if (UserManager.isLoginS()) {
            token = UserManager.getInstance().getToken();
        }
        if (intent != null) {
            url = intent.getStringExtra(EX_HTML);
            if (!TextUtils.isEmpty(url)) {
                JLog.e("htmlLogin", "----------load-------------token-" + token);
                if (!TextUtils.isEmpty(token)) {
                    if (!url.contains("?")) {
                        webView.loadUrl(url + "?token=" + token);
                    } else {
                        webView.loadUrl(url + "&token=" + token);
                    }
                } else {
                    webView.loadUrl(url);
                }
            }
        }
//        CookieSyncManager.createInstance(this);
//        CookieSyncManager.getInstance().sync();
    }

    /**
     * 回调的方法解析判断
     *
     * @param method
     * @param actId
     */
    private void parseJSMethod(String method, String actId) {
        method = method.trim();
        if ("Login".equalsIgnoreCase(method)) {
            //H5回调，判断是否已登录
            if (UserManager.isLoginS()) {
                token = UserManager.getInstance().getToken();
                if (!TextUtils.isEmpty(token)) {
                    JLog.e("htmlLogin", "-------is login-----token = " + token);
                } else {
                    toLogin();
                }
            } else {
                toLogin();
            }
        } else if ("Reg".equalsIgnoreCase(method)) {
//             toLogin();
        }
    }

    private void hideStatusBar() {
//        if (context instanceof FragmentActivity) {
//            FragmentActivity fragmentActivity = (FragmentActivity) context;
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
//        } else {
//            CommonUtil.getAppCompActivity(this).getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
//                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
//        }
    }

    private void initX5Setting() {
        WebSettings webSetting = webView.getSettings();
        String ua = webSetting.getUserAgentString();
        webSetting.setUserAgentString(ua + " SCGC_UA");
        webSetting.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSetting.setAllowFileAccess(true);
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSetting.setSupportZoom(false);
        webSetting.setBuiltInZoomControls(false);
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(false);
        // webSetting.setLoadWithOverviewMode(true);
        webSetting.setAppCacheEnabled(true);
        // webSetting.setDatabaseEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setJavaScriptEnabled(true);
        webSetting.setGeolocationEnabled(true);
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        webSetting.setAppCachePath(this.getDir("appcache", 0).getPath());
        webSetting.setDatabasePath(this.getDir("databases", 0).getPath());
        webSetting.setGeolocationDatabasePath(this.getDir("geolocation", 0)
                .getPath());
        // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 0:
                    if (null != uploadFile) {
                        Uri result = createUriResult(resultCode, data);

                        uploadFile.onReceiveValue(result);
                        uploadFile = null;
                    }
                    if (null != uploadFiles) {
                        Uri result = createUriResult(resultCode, data);

                        uploadFiles.onReceiveValue(new Uri[]{result});
                        uploadFiles = null;
                    }
                    break;
                case CODE_REQUEST_LOGIN:
                    //调用登陆页面，登陆成功回调
                    if (UserManager.isLoginS()) {
                        token = UserManager.getInstance().getToken();
                        if (!TextUtils.isEmpty(token)) {
                            JLog.e("htmlLogin", "----------re loadUrl ------------token-" + token);
                            webView.loadUrl(url + "?token=" + token);
                        }
                    }
                    break;
                default:
                    break;
            }
        } else if (resultCode == RESULT_CANCELED) {
            if (null != uploadFile) {
                uploadFile.onReceiveValue(null);
                uploadFile = null;
            }

        }
    }

    @Override
    public void onBackPressed() {
        if (webView == null || !webView.canGoBack()) {
            super.onBackPressed();
        } else {
            webView.goBack();
        }
    }

    @Override
    protected void onDestroy() {
        if (webView != null) {
            webView.removeAllViews();
            webView.destroy();
        }
        super.onDestroy();
    }

    @OnClick({R.id.title_top_layout_back, R.id.title_top_layout_edit})
    public void itemClick(View view) {
        switch (view.getId()) {
            case R.id.title_top_layout_back:
                finish();
                break;
            case R.id.title_top_layout_edit:
                if (!TextUtils.isEmpty(url)) {
                    FNews item = new FNews();
                    item.setNewsShareUrl(url);
                    if (TextUtils.isEmpty(title)) {
                        title = "四川观察·视频新闻第一屏";
                    }
                    item.setNewsTitle(title);
//                    this.setNewsId(item.getNewsId());
                    showShareFragment(item, new ShareFragment.OnShareFragmentClickListener() {
                        @Override
                        public void onClick(Pair<String, String> pairs) {
                        }
                    });
                } else {
                    toast(R.string.share_data_wrong);
                }
                break;


        }
    }

    private Uri createUriResult(int resultCode, Intent intent) {
        Uri result = intent == null || resultCode != RESULT_OK ? null
                : intent.getData();
        if (result == null && intent == null
                && resultCode == RESULT_OK) {
            File cameraFile = new File(mCameraFilePath);

            if (cameraFile.exists()) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    result = FileProvider.getUriForFile(this, getPackageName() + ".provider", cameraFile);
                } else {
                    result = Uri.fromFile(cameraFile);
                }
                sendBroadcast(new Intent(
                        Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, result));
            }
        }
        return result;
    }

    private void openFileChooseProcess(Intent intent) {
//        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
//        i.addCategory(Intent.CATEGORY_OPENABLE);
//        i.setType("*/*");
//        startActivityForResult(Intent.createChooser(i,"ttt"), 0);
        startActivityForResult(createDefaultOpenableIntent(intent), 0);
    }

    private Intent createDefaultOpenableIntent(Intent intent) {
        // Create and return a chooser with the default OPENABLE
        // actions including the camera, camcorder and sound
        // recorder where available.
        Intent chooser = createChooserIntent(createCameraIntent()
//                , createCamcorderIntent()
//                , createSoundRecorderIntent()
//                , createPicIntent()
        );
        if (intent == null) {
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("*/*");
        }
        chooser.putExtra(Intent.EXTRA_INTENT, intent);
        return chooser;
    }

    private Intent createChooserIntent(Intent... intents) {
        Intent chooser = new Intent(Intent.ACTION_CHOOSER);
//        chooser.addCategory(Intent.CATEGORY_OPENABLE);
        chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, intents);
        chooser.putExtra(Intent.EXTRA_TITLE, "File Chooser");
        return chooser;
    }

    private Intent createPicIntent() {
        Intent photoPickerIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        photoPickerIntent.addCategory(Intent.CATEGORY_OPENABLE);
        photoPickerIntent.setType("image/*");
        photoPickerIntent.putExtra(Intent.EXTRA_TITLE, "相册");
        return photoPickerIntent;
    }

    private Intent createCameraIntent() {
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        File externalDataDir = Environment
                .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        System.out.println("externalDataDir:" + externalDataDir);
        File cameraDataDir = new File(externalDataDir.getAbsolutePath()
                + File.separator + "browser-photo");
        cameraDataDir.mkdirs();
        mCameraFilePath = cameraDataDir.getAbsolutePath() + File.separator
                + System.currentTimeMillis() + ".jpg";
        System.out.println("mcamerafilepath:" + mCameraFilePath);
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                Uri.fromFile(new File(mCameraFilePath)));

        return cameraIntent;
    }

    private Intent createCamcorderIntent() {
        return new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
    }

    private Intent createSoundRecorderIntent() {
        return new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
    }
}
